<template>
    <div id="mapBoxId"></div>
    <div class="gisMapContent"></div>
</template>
<script lang="ts" setup>
import { TDMAP_TK } from '@/utils/constant';
import { View } from 'ol';
import TileLayer from 'ol/layer/Tile';
import { fromLonLat } from 'ol/proj';
import { XYZ } from 'ol/source';
import MapType from 'ol/Map.js';
import { defaults as defaultControls, MousePosition } from 'ol/control';
import { format } from 'ol/coordinate';
let map: MapType;
let xy: any;
/**
 * 图层
 */
const getLayers = () => {
    // 天地图矢量图层
    const tdMapVectorLayer = new TileLayer({
        zIndex: 30,
        className: 'tdVector',
        visible: true,
        source: new XYZ({
            url: `https://t0.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=${TDMAP_TK}`,
            wrapX: false
        })
    });
    // 天地图标注层
    const tdMapCvaLayer = new TileLayer({
        zIndex: 31,
        className: 'tdCva',
        visible: true,
        source: new XYZ({
            url: `https://t0.tianditu.gov.cn/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=${TDMAP_TK}`,
            wrapX: false
        })
    });
    const layers = [tdMapVectorLayer, tdMapCvaLayer];
    return layers;
};
/**
 * 初始化地图
 */
const initMap = () => {
    const layers = getLayers();
    const view = new View({
        center: fromLonLat([86.25903, 41.33632]),
        zoom: 16,
        minZoom: 9,
        maxZoom: 18,
        constrainResolution: true, // 设置缩放级别为整数
        smoothResolutionConstraint: false // 关闭无级缩放地图
    });
    map = new MapType({
        target: 'mapBoxId',
        layers,
        view,
        controls: defaultControls({
            zoom: false,
            rotate: false,
            attribution: false
        })
    });

    //鼠标获取坐标控件
    const mousePositionControl = new MousePosition({
        coordinateFormat: function (coordinate: any) {
            xy = format(
                coordinate,
                '经度:&nbsp{x}&nbsp&nbsp纬度:&nbsp{y}&nbsp&nbsp审图号: GS（2022）',
                2
            );
            return xy;
        },
        projection: 'EPSG:4326',
        className: 'custom-mouse-position',
        target: document.getElementById('gisMapContent') as HTMLElement,
    });
    map.addControl(mousePositionControl);
};

/**
 * 销毁左侧地图
 */
const distoryMap = () => {
    map && map.setTarget();
    map && map.dispose();
};
onMounted(() => {
    initMap();
});
onBeforeUnmount(() => {
    distoryMap();
});
</script>
<style lang="scss" scoped>
#mapBoxId {
    width: 100vw;
    height: 100vh;
}
.gisMapContent{
    position: fixed;
    bottom: 10px;
    right: 10px;
}
</style>
